package com.wel.onlineshopping.service;

import com.wel.onlineshopping.model.Product;
import com.wel.onlineshopping.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ProductService {
    @Autowired
    private ProductRepository productRepository;

    // 获取所有产品
    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }

    // 根据产品ID获取产品
    public Product getProductById(Long id) {
        return productRepository.findById(id).orElse(null);
    }

    // 添加新产品
    public Product addProduct(Product product) {
        return productRepository.save(product);
    }

    // 更新产品
    public Product updateProduct(Long productId, Product updatedProduct) {
        return productRepository.findById(productId).map(product -> {
            product.setName(updatedProduct.getName());
            product.setPrice(updatedProduct.getPrice());
            product.setDescription(updatedProduct.getDescription());
            return productRepository.save(product);
        }).orElse(null);
    }

    // 删除产品
    public void deleteProduct(Long productId) {
        productRepository.deleteById(productId);
    }
}

